<template>
  <a-modal
    width="80%"
    :visible="visible"
    :mask-closable="false"
    :confirm-loading="loading"
    ok-text="确认"
    cancel-text="取消"
    title="选择分支节点"
    :body-style="{
      padding: '12px 24px'
    }"
    :dialog-style="{
      top: '50px'
    }"
    @ok="handleOk"
    @cancel="cancel"
  >
    <div class="table_model">
      <div
        v-for="item in list"
        :key="item.id"
        class="sp_item"
      >
        <div class="title">
          {{
            item.subject
          }}
        </div>

        <div class="content">
          <!-- 人工决策 -->
          <div class="conten_item">
            <div class="conten_item_title">
              人工决策:
            </div>

            <div class="conten_real">
              <a-radio-group
                v-model="item.myDecision"
                :options="item.myFnodeNameMap"
                @change="(e) => changeDecision(e, item)"
              />
            </div>
          </div>

          <!-- 即将流向 -->
          <div class="conten_item">
            <div class="conten_item_title">
              即将流向:
            </div>

            <div class="conten_real">
              <a-checkbox
                :indeterminate="item.myIndeterminate"
                :checked="item.myCheckedAllFlow"
                @change="(e) => onCheckAllChange(item, e)"
              >
                全选
              </a-checkbox>
              <div style="margin-top: 10px;">
                <a-checkbox-group
                  v-model="item.myFlow"
                  :options="item.myFlows"
                  @change="flowChange(item)"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script>
import {
  handleNodeFreeSelectUser,
  doAction
} from '@/api/commonPropertypage/index';
import { getSidByDefKey } from '@/api/table';

const _ = require('lodash');

export default {
  name: 'MyDialog',

  props: {
    visible: {
      type: Boolean,
      default: false
    },

    dataList: {
      type: Array,
      default: () => []
    }
  },

  data() {
    return {
      list: [],
      loading: false
    };
  },

  watch: {
    visible: {
      handler: function(v) {
        if (v) {
          this.init();
        }
      }
    }
  },

  methods: {
    handleOk() {
      this.loading = true;

      this.$confirm(
        `此操作将提交此弹窗内的表单, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.submit();
      }).catch(() => {
        this.loading = false;
      });
    },

    submit() {
      const list = this.list;
      const subscriber = [];
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        const {
          myDecision: destination,
          myFlow,
          myFlows,
          bizKey: formGuid,
          nodeId,
          matterSxuuid,
          instId: instanceId,
          taskId,
          defId,
          myFnodeIdentitysMap
        } = item;

        if (!destination) {
          this.$message.warning('第' + i + 1 + '行人工决策不能为空');
          return;
        }

        const nodeUsers = myFlow.length ? myFlow : myFlows.map(o => o.value);
        const users = myFnodeIdentitysMap[destination];

        const requestData = {
          action: 'agree',
          extendConf: { nodeId: '' },
          opinion: '同意',
          data: {
            test: 'jeff'
          },
          test: 'jeff',
          formType: 'FRAME',

          formGuid,
          nodeId,
          matterSxuuid,
          instanceId,
          taskId,
          defId,
          destination,
          nodeUsers: {
            [destination]: users.filter(user => {
              if (nodeUsers.includes(user.id)) {
                return true;
              }
            })
          }
        };

        /*         const requestData1 = {
          bpmBody: {
            action: 'agree',
            destination,
            defId,
            opinion: '同意',
            taskId,
            taskIds: '',
            instanceId,
            extendConf: { nodeId: '' },
            nodeUsers: {
              [destination]: nodeUsers
            },
            defKey: '',
            sId: '', // ?
            year: new Date().getFullYear() + '',
            type: '',
            linkPhone: '',
            linkName: '',
            formGuid
          },
          bodyData: [],
          formGuid,
          tableDate: '',
          userId: '',
          menuId: ''
        }; */

        const waiting = new Promise((r, j) => {
          doAction(requestData).then(res => {
            const { success } = res;
            if (success) {
              r(res);
            } else {
              j(res);
            }
          }).catch(e => {
            j(e);
          });
        });

        subscriber.push(waiting);
      }

      Promise.allSettled(subscriber).then(results => {
        let flag = true;
        for (let i = 0; i < results.length; i++) {
          const res = results[i];
          const {
            status,
            reason
          } = res;
          if (status === 'rejected') {
            flag = false;
            this.$message.warning('第' + (i + 1) + '个表单提交失败:' + reason.message);
          }
        }
        this.loading = false;

        if (flag) {
          this.$message.success('提交成功');
          this.$emit('updateValue');
          this.cancel();
        }
      });
    },

    cancel() {
      if (this.loading) {
        this.$message.warning('数据正在提交中，请稍后');
      } else {
        this.$emit('update:visible', false);
      }
    },

    init() {
      const list = _.cloneDeep(this.dataList);
      const subscriber = [];

      list.map(o => {
        const {
          instId: instanceId,
          nodeId,
          taskId,
          defKey
          // bizKey: formGuid
        } = o;

        // 人工决策值
        o.myDecision = '';
        // 即将流向值
        o.myFlow = [];
        o.myCheckedAllFlow = false;
        o.myIndeterminate = false;

        const requestData = {
          action: 'agree',
          data: {},
          extendConf: { nodeId: '' },
          instanceId,
          nodeId,
          taskId
        };

        const selUserPromise = handleNodeFreeSelectUser(requestData).then(res => {
          if (res.success) {
            const nodeIdentitysMap = res.data.nodeIdentitysMap;
            if (nodeIdentitysMap) {
              for (const key in nodeIdentitysMap) {
                const users = nodeIdentitysMap[key];
                nodeIdentitysMap[key] = users.map(user => ({
                  ...user,
                  label: user.name,
                  value: user.id
                }));
              }
            }
            o.myFreeSelectNode = res.data.freeSelectNode;
            o.myFnodeIdentitysMap = nodeIdentitysMap;
            o.myFnodeNameMap = Object.keys(res.data.nodeNameMap).map(key => {
              return {
                label: res.data.nodeNameMap[key],
                value: key
              };
            });

            o.myDecision = o.myFnodeNameMap[0] && o.myFnodeNameMap[0].value || '';
            o.myFlows = o.myDecision && o.myFnodeIdentitysMap[o.myDecision] || [];
          }
          return Promise.resolve(res);
        });
        const sidPromise = getSidByDefKey({ key: defKey }).then(res => {
          if (res.success) {
            const {
              matterSxuuid
            } = res.data;

            o.matterSxuuid = matterSxuuid;
          }
          return Promise.resolve(res);
        });
        subscriber.push(selUserPromise, sidPromise);
      });

      Promise.allSettled(subscriber).then(() => {
        this.list = list;
      });
    },

    flowChange(item) {
      const {
        myFlow,
        myFlows
      } = item;

      const seLen = myFlow.length;
      const selsLen = myFlows.length;

      item.myIndeterminate = seLen && seLen < selsLen || false;
      item.myCheckedAllFlow = seLen === selsLen;
    },

    changeDecision(e, item) {
      const {
        myDecision,
        myFnodeIdentitysMap
      } = item;
      item.myFlow = [];
      item.myCheckedAllFlow = false;
      item.myIndeterminate = false;
      item.myFlows = myFnodeIdentitysMap[myDecision];
    },

    onCheckAllChange(item, e) {
      const value = e.target.checked;
      const checked = value ? item.myFlows.map(o => o.value) : [];
      Object.assign(item, {
        myCheckedAllFlow: value,
        myFlow: checked,
        myIndeterminate: false
      });
    }
  }
};
</script>

<style lang="scss" scoped>
  .table_model{
    min-height: 60vh;
    max-height: 60vh;
    overflow: auto;

    display: grid;

    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 12px 20px;

    .sp_item {
      height: 550px;
      display: flex;
      flex-direction: column;
      .title{
        font-size: 16px;
        color: #4F4F4F;
      }
      .content {
        background-color: #99CBF9;
        flex: 1;
        border-radius: 4px;
        padding: 16px 10px;
        overflow: auto;
        display: flex;
        flex-direction: column;
        gap: 10px;

        .conten_item {
          flex: 1;
          overflow: hidden;
          font-size: 16px;
          display: flex;
          flex-direction: column;

          .conten_item_title {
            padding: 0 0 8px 8px;
            color: #ffffff;
          }

          .conten_real {
            padding: 8px;
            flex: 1;
            background: rgba(255,255,255,0.85);
            border-radius: 4px;
            overflow: auto;
          }
        }
      }
    }
  }
</style>
